package com.utils;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;

/**
 * Created by tanyan on 2018-05-10.
 * 全局异常处理器
 */
public class MyCrashHandler implements UncaughtExceptionHandler {
    private static MyCrashHandler myCrashHandler;
    private Context context;
    private String os_version;

    private MyCrashHandler() {
    }

    public static synchronized MyCrashHandler getInstance() {
        if (myCrashHandler != null) {
            return myCrashHandler;
        } else {
            myCrashHandler = new MyCrashHandler();
            return myCrashHandler;
        }
    }

    public void init(Context context) {
        this.context = context.getApplicationContext();
        FileLog.setLogPath(PathUtils.getInstance().getFYLogPath());
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    public void uncaughtException(Thread t, Throwable th) {
        try {
            String errorinfo = getErrorInfo(th);
            String headstring = "";
            int nIndex = -1;
            if ((nIndex = errorinfo.indexOf("Caused by:")) >= 0) {
                String ssString = errorinfo.substring(nIndex);
                String[] ss = ssString.split("\n\t");
                headstring = ss[0] + "\n\t" + ss[1] + "\n\t" + ss[2] + "\n\t";
            }
            os_version = getOsVersion(context);
            String stacktrace = "Crached:\r\n" + "os_version:" + os_version
                    + "\r\n";
            stacktrace += "deviceid:" + Build.MANUFACTURER + Build.PRODUCT
                    + "\r\n";
            stacktrace += headstring + errorinfo;
            Log.e("CrashHandler", headstring);
            Log.e("CrashHandler", headstring + errorinfo);
//            if (!TransUtils.getDebuggable() && !TextUtils.isEmpty(headstring)) {
//                //错误统计
//                MobclickAgent.reportError(context, headstring);
//            }

            if (!TextUtils.isEmpty(stacktrace)) {
                //错误统计
//                MobclickAgent.reportError(context, stacktrace);
            }
            FileLog.writeLog(stacktrace.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private String getErrorInfo(Throwable t) {
        Writer writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        t.printStackTrace(pw);
        pw.close();
        String error = writer.toString();
        return error;
    }

    /**
     * get OS number
     *
     * @param context
     * @return
     */
    public static String getOsVersion(Context context) {
        String osVersion = Build.VERSION.RELEASE;
        return osVersion;
    }

}